package com.sky.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 获取锁：原子操作，返回true表示成功
    public boolean tryLock(String lockKey, long timeout, TimeUnit unit) {
        String lockValue = UUID.randomUUID().toString();
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(lockKey, lockValue, timeout, unit);
        return Boolean.TRUE.equals(success);
    }

    // 释放锁：仅删除自己持有的锁
    public void unlock(String lockKey) {
        String lockValue = stringRedisTemplate.opsForValue().get(lockKey);
        if (lockValue != null) {
            stringRedisTemplate.delete(lockKey);
        }
    }
}
